﻿using Ids4.Api.Models;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace Ids4.Api.Application.Middleware
{
    /// <summary>
    /// GlobalExceptionMiddleware
    /// </summary>
    public class GlobalExceptionMildd
    {
        private readonly RequestDelegate next;
        /// <summary>
        /// GlobalExceptionMiddleware
        /// </summary>
        /// <param name="next"></param>
        public GlobalExceptionMildd(RequestDelegate next)
        {
            this.next = next;
        }
        /// <summary>
        /// Invoke
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }
        /// <summary>
        /// HandleExceptionAsync
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            int code = (int)ResultCode.GLOBAL_ERROR;
            string msg;
            if (ex is ArgumentException)
            {
                code = (int)ResultCode.PARAM_ERROR;
                msg = ex.Message;
                NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Web, "参数异常", "参数异常", ex);
            }
            else
            {
                msg = "服务器好像出了点问题......";
                NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Web, "异常", $"开始推送服务器异常:code={code},msg={msg}{ex.Message},请求方式:{context.Request.Method},请求url:{context.GetRequestUrl()},请求参数:{await context.GetRequestValue()}", ex);
                context.Response.StatusCode = 500;
            }

            var options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            };

            ApiResult apiResult = new(code, msg);
            string responseResult = System.Text.Json.JsonSerializer.Serialize(apiResult, options).ToLower();
            context.Response.ContentType = "text/json;charset=utf-8";
            await context.Response.WriteAsync(responseResult, System.Text.Encoding.UTF8);
        }
    }
}
